﻿using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine.SocialPlatforms;

namespace MyTanks
{
    [BurstCompile]
    public partial struct ShellSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Shell>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var config = SystemAPI.GetSingleton<MyTanksConfig>();

            var shellJob = new ShellJob
            {
                deltaTime = SystemAPI.Time.DeltaTime,
                speed = config.shellFlySpeed,
                gravityRatio = config.gravityRatio
            };

            shellJob.ScheduleParallel();
        }
    }


    public partial struct ShellJob : IJobEntity
    {
        public float deltaTime;
        public float speed;
        public float gravityRatio;

        void Execute(Entity entity, ref Shell shell, ref LocalTransform transform)
        {
            var gravity = new float3(0.0f, -9.82f * gravityRatio, 0.0f);

            transform.Position += shell.velocity * deltaTime * speed;
            shell.velocity += gravity * deltaTime;
            shell.duration += deltaTime;
            transform.Rotation = quaternion.LookRotationSafe(shell.velocity, new float3(0, 1, 0));

            if (shell.duration >= 2)
            {
                shell.duration = 0;
                World.DefaultGameObjectInjectionWorld.EntityManager.SetComponentEnabled<ShellIsIdle>(entity, true);
            }
        }
    }
}